// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package manager

import (
	"fmt"
	"os"

	"github.com/fatih/color"
	"github.com/kumose/kmopt/pkg/cluster/clusterutil"
	operator "github.com/kumose/kmopt/pkg/cluster/operation"
	"github.com/kumose/kmopt/pkg/cluster/spec"
	"github.com/kumose/kmopt/pkg/tui"
	"github.com/kumose/kmopt/pkg/utils"
)

// Rename the cluster
func (m *Manager) Rename(name string, opt operator.Options, newName string, skipConfirm bool) error {
	if err := clusterutil.ValidateClusterNameOrError(name); err != nil {
		return err
	}
	if !utils.IsExist(m.specManager.Path(name)) {
		return errorRenameNameNotExist.
			New("Cluster name '%s' not exist", name).
			WithProperty(tui.SuggestionFromFormat("Please double check your cluster name"))
	}

	if err := clusterutil.ValidateClusterNameOrError(newName); err != nil {
		return err
	}
	if utils.IsExist(m.specManager.Path(newName)) {
		return errorRenameNameDuplicate.
			New("Cluster name '%s' is duplicated", newName).
			WithProperty(tui.SuggestionFromFormat("Please specify another cluster name"))
	}

	if !skipConfirm {
		if err := tui.PromptForConfirmOrAbortError(
			"%s", fmt.Sprintf("Will rename the cluster name from %s to %s.\nDo you confirm this action? [y/N]:", color.HiYellowString(name), color.HiYellowString(newName)),
		); err != nil {
			return err
		}
	}

	_, err := m.meta(name)
	if err != nil { // refuse renaming if current cluster topology is not valid
		return err
	}

	if err := os.Rename(m.specManager.Path(name), m.specManager.Path(newName)); err != nil {
		return err
	}

	m.logger.Infof("Rename cluster `%s` -> `%s` successfully", name, newName)

	opt.Roles = []string{spec.ComponentGrafana, spec.ComponentPrometheus}
	return m.Reload(newName, opt, false, skipConfirm)
}
